package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {


    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        studentService = wac.getBean(StudentService.class);
    }

    // 根据请求参数的值电泳不同的方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String cmd = req.getParameter("cmd");
        if (StringUtils.isNotBlank(cmd)) {

            if ("list".equals(cmd)) {
                list(req,resp);
            }
        }


    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Student> studentList = studentService.findAll();
        resp.getWriter().println(JSON.toJSONString(studentList));
        resp.getWriter().close();
    }
}
